package com.lolaage.tracks.content;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.lolaage.tracks.Track;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-9-7
 * @see : 轨迹的列表
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
class TracksDB extends DB
{   
    private static enum UPDATE_TYPE
    {
        NEW,NAME,LOCATION,COPY
    }
    private static final String TAG = "TracksDB";
    public static final String TABLE_NAME = "tracks";
    
    public static final String CID = "clientId";
    public static final String NAME = "name";
    public static final String TIME = "time";
    public static final String START_PID = "startPid";
    public static final String START_TIME = "startTime";
    public static final String END_PID = "endPid";
    public static final String END_TIME = "endTime";
    public static final String TOTAL_DISTANCE = "totalDistance";
    
    private static int BASE_INDEX = 0;
    private static final int INDEX_ID = BASE_INDEX;
    private static final int INDEX_CID= ++BASE_INDEX;
    private static final int INDEX_NAME= ++BASE_INDEX;
    private static final int INDEX_TIME= ++BASE_INDEX;
    private static final int INDEX_START_PID = ++BASE_INDEX;
    private static final int INDEX_START_TIME = ++BASE_INDEX;
    private static final int INDEX_END_PID = ++BASE_INDEX;
    private static final int INDEX_END_TIME = ++BASE_INDEX;
    private static final int INDEX_TOTAL_DISTANCE = ++BASE_INDEX;
    
    public static final String SQL_CREATE = "CREATE TABLE[" + TABLE_NAME + "] ("
        + "[" + _ID + "] INTEGER PRIMARY KEY autoincrement," 
        + "[" + CID+ "] INTEGER NOT NULL, " 
        + "[" + NAME+ "] STRING DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now')),"
        + "[" + TIME+ "] INTEGER default current_timestamp,"
        + "[" + START_PID + "] INTEGER default (0)," 
        + "[" + START_TIME + "] INTEGER default current_timestamp," 
        + "[" + END_PID + "] INTEGER default (0)," 
        + "[" + END_TIME + "] INTEGER default current_timestamp," 
        + "[" + TOTAL_DISTANCE + "] FLOAT default (0)"
        + ");";
       
    /** 新建一个轨迹 */
    public Track newTrack(int clientId)
    {
        SQLiteDatabase db = getDB(true);
        ContentValues cv = new ContentValues();
        cv.put(CID, clientId);
        long trackid = db.insert(TABLE_NAME, CID, cv);
        if (trackid > 0)
        {
            return new Track(trackid, clientId);
        } else
        {
            return null;
        }
    }
    
    /** 获取最后的一个轨迹*/
    public Track getLastTrack(int clientId)
    {
        SQLiteDatabase db = getDB(false);       
        Cursor c = null;
        String section = CID + "=" + clientId;
        String orderBy = _ID + " desc";
        String limit   = "0,1";
        try
        {
            c = db.query(TABLE_NAME, null, section, null, null, null, orderBy, limit);
            if(c.moveToNext())
            {
                return fill(c);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != c)
            {
                c.close();
            }
        }
        return null;
    }
    
    /** 更新轨迹*/
    public boolean updateTrack(Track track)
    {
        SQLiteDatabase db = getDB(true);       
        return db.update(TABLE_NAME, toContentValues(track, UPDATE_TYPE.LOCATION), _ID +"="+track._id, null) > 0;
    }
    
    /** 获取轨迹列表*/
    public List<Track> getTrackList(int clientId,int page, int num, boolean last)
    {
        String section = CID + "=" + clientId;
        String orderBy = TIME + ( last ? " DESC " : " ASC ");
        String limit   = page > 0 ? page*num + "," + num : null;
        SQLiteDatabase db = getDB(false);
        
        Cursor cursor = null;
        try 
        {
            cursor = db.query(TABLE_NAME, null, section, null, null, null, orderBy, limit);
            List<Track> points = new ArrayList<Track>(cursor.getCount());
            while(cursor.moveToNext())
            {
                points.add(fill(cursor));
            }
            return points;
        }catch(SQLiteException e)
        {
            e.printStackTrace();
        }finally 
        {
            if(cursor != null)
            {
                cursor.close();
                cursor = null;
            }
        }
        return null;
    }
    
    /** 删除轨迹*/
    public boolean deleteTrack(long trackId)
    {      
        return clear(TABLE_NAME, _ID + "=" + trackId);
    }
    
    /** 删除所有轨迹*/
    public boolean deleteAllTrack(int clientId)
    {
        return clear(TABLE_NAME, CID + "=" + clientId);
    }
   
    public static ContentValues toContentValues(Track track, UPDATE_TYPE type)
    {
        ContentValues cv = new ContentValues();
        
        if(type == UPDATE_TYPE.NEW || type == UPDATE_TYPE.COPY)
        {
            cv.put(CID, track.clientId);
        }
        if(type == UPDATE_TYPE.NAME || type == UPDATE_TYPE.COPY)
        {
            cv.put(NAME, track.name);
        }
        if(type == UPDATE_TYPE.COPY)
        {
            cv.put(TIME, track.time);
        }
        if(type == UPDATE_TYPE.LOCATION || type == UPDATE_TYPE.COPY)
        {
            cv.put(START_PID, track.startPid);
            cv.put(START_TIME, track.startTime);
            cv.put(END_PID, track.endPid);
            cv.put(END_TIME, track.endTime);
            cv.put(TOTAL_DISTANCE, track.totalDistance);
        }
        return cv;
    }
    
    private static Track fill(Cursor cursor)
    {       
        Track track = new Track();
        
       track._id = cursor.getLong(INDEX_ID);
       track.name = cursor.getString(INDEX_NAME);
       track.time = cursor.getLong(INDEX_TIME);
       track.clientId = cursor.getInt(INDEX_CID);
       track.startPid = cursor.getLong(INDEX_START_PID);
       track.startTime = cursor.getLong(INDEX_START_TIME);
       track.endPid = cursor.getLong(INDEX_END_PID);
       track.endTime = cursor.getLong(INDEX_END_TIME);
       track.totalDistance = cursor.getFloat(INDEX_TOTAL_DISTANCE);
       
       return track;
    }
}
